/**
 *
 * Copyright 2012 TeleNav, Inc. All rights reserved.
 * AsyncImageLoader.java
 * @author jwmeng (jwmeng@telenavsoftware.com)
 * @date 2012-10-19
 */
package com.telenav.util;

import java.util.HashMap;

import android.graphics.Bitmap;
import android.os.Handler;
import android.widget.ImageView;

public class AsyncImageLoader{

  private HashMap<String, Bitmap> imageMap;
  private static AsyncImageLoader instance;
  private Handler handler; 

  private AsyncImageLoader(){

    imageMap = new HashMap<String, Bitmap>();

    handler = new Handler();

  }
  
  public static AsyncImageLoader getInstance()
  {
	  if(instance == null)
		  instance = new AsyncImageLoader();
	  return instance;
  }

  public void loadImage(final String imageUrl, final ImageView imageView, final int resId){

    new Thread(new Runnable() {
      public void run() {

        Bitmap image = imageMap.get(imageUrl);
        if (image == null) {
        	
         handler.post(new Runnable() {
                public void run() 
                {
              	  if(imageView != null)
              	  {
              		imageView.setImageResource(resId);
              	  }
              	  
                }
          });

          image = ApacheUtility.GetBitmapByUrl(imageUrl);

          imageMap.put(imageUrl, image);

        }

        final Bitmap bitmap = image;
        handler.post(new Runnable() {
          public void run() 
          {
        	  if(imageView != null && bitmap != null)
        	  {
        		  imageView.setImageBitmap(bitmap);
        	  }
        	  
          }
        });

      }
    }).start();

  }

}